//
//  LiuComposePicView.swift
//  LiuWeiBo
//
//  Created by 刘晓晨 on 2017/4/5.
//  Copyright © 2017年 刘晓晨. All rights reserved.
//

import UIKit

class LiuComposePicView: UICollectionView {
    
    //懒加载控件
    lazy var picArray:[UIImage] = [UIImage]()
    
    //点击加号cell回调
    var addPicClosure:(()->())?
    
    var imageCountChangeClosure:((Int)->())?

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        //每项的间距
        let itemMargin:CGFloat = 5
        
        //每项的宽度和高度
        let itemWidth = (screenWidth - 2 * homeMargin - 2 * itemMargin)/3
        let itemHeight = itemWidth
        
        let flowLayout = UICollectionViewFlowLayout()
        
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemHeight)
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    fileprivate func setupUI() {
        backgroundColor = UIColor.red
        
        //上来隐藏
        self.isHidden = true
        
        //遵守数据源,代理
        delegate = self
        dataSource = self
        
        //注册cell
        register(LiuComposePicViewCell.self, forCellWithReuseIdentifier: composePicCellId)
    }
    
    func addImage(image:UIImage) {
        
        if picArray.count >= 9 {
            return
        }
        
        //显示图片view
        isHidden = false
        
        //添加到数组中
        picArray.append(image)
        
        //显示右侧按钮
        imageCountChangeClosure?(picArray.count)
        
        //重新加载数据
        reloadData()
    }
}

extension LiuComposePicView:UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if picArray.count == 0 || picArray.count == 9 {
            return picArray.count
        }
        return picArray.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:LiuComposePicViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: composePicCellId, for: indexPath) as! LiuComposePicViewCell
        if indexPath.item == picArray.count {
            cell.image = nil
        } else {
            cell.image = picArray[indexPath.item]
            cell.indexPath = indexPath
            
            //删除按钮点击回调
            cell.buttonActionClosure = { [weak self] (index:Int)->() in
                if let weakSelf = self {
                    weakSelf.picArray.remove(at: index)
                    
                    if weakSelf.picArray.count == 0 {
                        weakSelf.isHidden = true
                        
                        //回调
                        weakSelf.imageCountChangeClosure?(weakSelf.picArray.count)
                    }
                    
                    weakSelf.reloadData()
                }
                
            }
        }
        
        return cell
        
    }
    
    ///点击"+"号cell添加图片
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item == picArray.count {
            addPicClosure?()
        }
    }
    
}


class LiuComposePicViewCell: UICollectionViewCell {
    
    
    /// 懒加载图片view
    fileprivate lazy var imageView:UIImageView = UIImageView()
    
    //懒加载删除按钮
    fileprivate lazy var cacelButton:UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named:"compose_photo_close"), for: .normal)
        button.addTarget(self, action: #selector(buttonAction(btn:)), for: .touchUpInside)
        return button
    }()
    
    ///传递过来的indexPath
    var indexPath:IndexPath?
    
    
    ///回调闭包
    var buttonActionClosure: ((Int)->())?
    
    /// 传递过来的图片设置到imageView上
    var image:UIImage? {
        didSet {
            if image != nil {
                imageView.image = image
                cacelButton.isHidden = false
            } else {
                imageView.image = UIImage(named: "compose_pic_add")
                cacelButton.isHidden = true
            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func setupUI() {
        
        addSubview(imageView)
        addSubview(cacelButton)
        
        cacelButton.snp.makeConstraints { (make) in
            make.right.top.equalToSuperview()
        }

        imageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    //删除按钮点击
    @objc fileprivate func buttonAction(btn:UIButton) {
        if let index = indexPath?.item {
            buttonActionClosure?(index)
        }
    }
    
}









